#include "StreamClient_Acceptor.h"
#include "StreamClient_Handle.h"
#include "CameraManager.h"


int CStreamClient_Acceptor::open (u_short serverport) 
{
	ACE_INET_Addr local_addr;
	if (local_addr.set(serverport) == -1)
		ACE_ERROR_RETURN ( (LM_ERROR, "set local address at %d %p\n", 
		serverport, "failed"), -1 );

	if (acceptor_.open (local_addr) == -1) 
		ACE_ERROR_RETURN ( (LM_ERROR, "listen TCP local address at %d %p(%d)\n", 
		serverport, "failed"), -1 );

	ACE_DEBUG ( ( LM_DEBUG, "Begin to listen TCP port %d ...\n", serverport));

	//acceptor_.enable(ACE_NONBLOCK)

	return reactor()->register_handler(this, ACE_Event_Handler::ACCEPT_MASK);
}

int CStreamClient_Acceptor::handle_input (ACE_HANDLE) 
{

	StreamClient_Handle *pHandler = new StreamClient_Handle(reactor());
	ACE_ASSERT(pHandler!=NULL);
	ACE_INET_Addr l_addr;


	if (acceptor_.accept (pHandler->peer (), 
		&(l_addr), &ACE_Time_Value(0, 1000)) == -1) 
	{
		ACE_DEBUG ( (LM_ERROR, "accept one clinet %p\n", "failed"));
		delete pHandler;
		return -1;
	} 
	else 
	{
		pHandler->addr() = l_addr;

		ACE_DEBUG ( ( LM_DEBUG, "tcp client %s:%d connect in\n", 
			l_addr.get_host_addr(), l_addr.get_port_number() ) );

		if (pHandler->open() == -1) {
			ACE_DEBUG ( ( LM_DEBUG, "make client tcp connection to %s:%d %p\n",
				pHandler->addr().get_host_addr(), 
				pHandler->addr().get_port_number(), 
				"failed") );
			//pHandler->handle_close();
			return 0;
		}
	
		CameraManager::instance()->tcpclient_Map[pHandler] = NULL;
	}
	return 0;
}

int CStreamClient_Acceptor::handle_close (ACE_HANDLE, ACE_Reactor_Mask) 
{
	ACE_DEBUG((LM_DEBUG,"End to listen TCP.... \n"));

	acceptor_.close();
//	delete this;

	return 0; 
}
